package com.ys.controller.api.business;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ys.entity.business.TpShopRegisterPhaseRecord;
import com.ys.entity.business.TpShopRegisterPhaseSet;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.sys.YsCol;
import com.ys.service.business.TpHolidaySetService;
import com.ys.service.business.TpShopRegisterPhaseRecordService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

/**
 * 店铺注册跟踪
 */
@Controller
@RequestMapping("/api/inter/tpShopRegisterPhaseRecord")
public class ApiInterTpShopRegisterPhaseRecordController {
    private static Long MENU_ID = 55L;

    @Autowired
    private CommonApiService<TpShopRegisterPhaseRecord> commonApiService;
    @Autowired
    private CommonApiService<ThrOperateCompanyApply> commonApiServiceByThrOperateCompanyApply;
    @Autowired
    private TpShopRegisterPhaseRecordService tpShopRegisterPhaseRecordService;
    @Autowired
    private TpHolidaySetService tpHolidaySetService;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TpShopRegisterPhaseRecord setSeachSql(TpShopRegisterPhaseRecord cond){
        cond.addField("O.VGsMc AS vGsMc");//运营公司
        cond.addField("O.VGsJc AS vGsJc");//公司简称
        cond.addField("O.VGsBm AS vGsBm");//运营公司编码
        cond.addField("U.UserId + '/' + U.UserName AS operateUser ");//运营人
        cond.addField("U.DeptName AS vYyJb");//运营组别，所属部门
        cond.addField("CASE WHEN PO.OperatorChangeId IS NULL THEN '' ELSE PU.UserId + '/' + PU.UserName END pOperateUser ");//运营人上级
        cond.addField("PU.DeptName AS pVYyJb ");//运营组别上级，所属部门上级
        cond.addField("S.ShopName AS shopName ");//网店名称
        cond.addField("CASE WHEN A.HeadUserId IS NULL OR A.HeadUserId = '' THEN '未完成' WHEN A.RealityWorkTime > A.WorkTime THEN '是' ELSE '否' END isOver ");//是否超时
        cond.addField("CASE WHEN A.HeadUserId IS NULL OR A.HeadUserId = '' THEN SS.WorkTime ELSE A.WorkTime END workTimeInfo ");//时效
        cond.addField("TU.theUserId + '/' + TU.theUserName AS headUser ");//负责人
        cond.addField("TU.theUserId AS theHeadUserId ");//负责人id，用于配置数据权限
        cond.addField("TU.theDeptName AS deptName ");//负责部门
        cond.addField("CASE WHEN A.PhaseName IS NULL OR A.PhaseName = '' THEN SS.PhaseName ELSE A.PhaseName END thePhaseName ");//阶段名称
        //关联用户表；未完成的跟踪单，用户信息来自阶段设置表；完成的跟踪单，用户信息来自跟踪单记录表
        cond.addLeftJoin("( SELECT " +
                "CASE WHEN S.HeadUserId IS NULL OR S.HeadUserId = '' THEN SS.HeadUserId ELSE S.HeadUserId END theUserId, " +
                "CASE WHEN S.HeadUserId IS NULL OR S.HeadUserId = '' THEN UI.DeptName ELSE U.DeptName END theDeptName, " +
                "CASE WHEN S.HeadUserId IS NULL OR S.HeadUserId = '' THEN UI.UserName ELSE U.UserName  END theUserName,"+
                "S.SetId , S.OperateCompanyId  " +
                "FROM " +
                "TP_ShopRegisterPhaseRecord S " +
                "LEFT JOIN TP_ShopRegisterPhaseSet SS ON SS.Id = S.SetId " +
                "LEFT JOIN TS_UserChange U ON S.HeadUserId = U.UserId " +
                "LEFT JOIN TS_UserChange UI ON SS.HeadUserId = UI.UserId WHERE U.Status = 1 AND UI.Status = 1) TU  ON TU.OperateCompanyId = A.OperateCompanyId");
        //关联运营公司备案表
        cond.addLeftJoin("THR_OperateCompanyApply O ON O.Id = A.OperateCompanyId ");
        //关联运营公司备案表-上级
        //cond.addLeftJoin("THR_OperateCompanyApply PO ON PO.VGsBm = O.VGsBmP ");
        cond.addLeftJoin("TS_UserChange U ON U.Id = O.OperatorChangeId");
        cond.addLeftJoin("TS_OrganizationInfo UO ON UO.Orgid = U.DeptId");

        //关联运营公司管理表-上级
        cond.addLeftJoin("TS_OperateOrg ORG ON ORG.Id = O.OperateOrgId ");
        cond.addLeftJoin("THR_OperateCompanyApply PO ON PO.VGsBm = ORG.HeadVgsbm AND 1=1 ");
        cond.addLeftJoin("TS_UserChange PU ON U.Id = PO.OperatorChangeId AND 1=1 ");
        cond.addLeftJoin("TS_OrganizationInfo PUO ON PUO.Orgid = PU.DeptId");

        //关联网店信息表
        cond.addLeftJoin("TP_AmazonShop S ON S.Id = A.AmazonShopId ");
        //关联阶段设置表,不能根据上面关联的TU表查询
        cond.addLeftJoin("TP_ShopRegisterPhaseSet SS ON SS.Id = A.SetId ");

        cond.where("TU.SetId = A.SetId AND A.SetType = 0");

        return  cond;
    }

    //处理返回的数据
    public List setList(List<Map<String, Object>> resDate){
        List<Map<String, Object>> tableDate = new ArrayList();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //处理数据,实时计算预计完成时间、已工作时间
        resDate.forEach(item->{

            if(item.get("realityWorkTime") ==null){
                String dateString = item.get("startTime").toString();
                Date startDate = null;
                try {
                    startDate = dateFormat.parse(dateString);
                    BigDecimal workTimeInfo = (BigDecimal) item.get("workTimeInfo");//时效
                    int workDay = workTimeInfo!=null?workTimeInfo.intValue():0;
                    Date planEndTimeInfo = tpHolidaySetService.countEndTimeSkipWorkDate( startDate, workDay, 1);
                    item.put("planEndTimeInfo",dateFormat.format(planEndTimeInfo));

                    Date day=new Date();
                    //计算到今日为止的工作时间
                    int workTimeCount = tpHolidaySetService.checkOverTime( startDate, day, 1);
                    item.put("workTimeCount",workTimeCount);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }else {
                item.put("planEndTimeInfo",item.get("planEndTime"));
                item.put("workTimeCount",item.get("realityWorkTime"));
            }
            tableDate.add(item);
        });
        return tableDate;
    }

    /**
     * 查询
     * @param model
     * @param request
     * @param response
     * @param cond
     * @return
     */
    @RequiresPermissions("tpShopRegisterPhaseRecord:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TpShopRegisterPhaseRecord cond){
        try {

            cond = setSeachSql(cond);

            //关联自己，只查询最新阶段的数据
            //cond.addLeftJoin(" ( SELECT MAX ( PhaseNum ) AS PhaseNum, OperateCompanyId FROM TP_ShopRegisterPhaseRecord GROUP BY OperateCompanyId ) B ON B.OperateCompanyId = A.OperateCompanyId ");
            //cond.where("A.PhaseNum = B.PhaseNum ");
            cond.where("A.IsShow = 1 ");
            cond.setOrderby("A.UpdateTime DESC");//按修改时间倒序

    		cond = commonApiService.dataAuth(MENU_ID, cond);



            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            //获取
            JSONArray tableVoJAData = tableVoJA.getData();

            //转换
            List<Map> resList = JSONArray.parseArray(JSON.toJSONString(tableVoJAData),Map.class);
            List<Map<String, Object>> resListNew = new ArrayList();
            resList.forEach(item-> resListNew.add(item));

            //处理数据
            resList = setList(resListNew);
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resList));
            tableVoJA.setData(jsonArray);


            return tableVoJA;
        }catch (Exception e){
            e.printStackTrace();
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     * @param cond
     * @return
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TpShopRegisterPhaseRecord cond){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //cond.setOrderby("A.OperateCompanyId ASC,A.PhaseNum ASC ");//按运营公司，再按阶段顺序排序
            cond.setOrderby("A.OperateCompanyId ASC,A.Id ASC ");//按运营公司，再按修改时间排序
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            listData = setList(listData);

            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MENU_ID)
                    .where("A.Code != 'ope'")
                    .setOrderby("A.SortNo asc")
                    .queryList();


            ExportExcelUtils<TpShopRegisterPhaseRecord> util = new ExportExcelUtils<>(new TpShopRegisterPhaseRecord());
            
            String toFilePath = util.exportExcel(listData, listField, "店铺注册跟踪单");
            UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            e.printStackTrace();
            return R.error("导出失败，请稍后重试！");
        }
    }



    /**
     * 新增页面查询没有进行跟踪的运营公司备案信息
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/searchOperateCompanyNoRecord")
    @ResponseBody
    public LayuiTableVoJA searchOperateCompanyNoRecord(Model model, HttpServletRequest request, HttpServletResponse response,
                                                       @ModelAttribute ThrOperateCompanyApply cond
    ){
        try {

            cond.addField("A.Vgsbm AS vGsBm");
            cond.addField("A.Vgsmc AS vGsMc");
            cond.addField("A.Vgsjc AS vGsJc");
            cond.addField("A.Cuser AS cUser");
            cond.where("( SELECT COUNT ( 1 ) AS num FROM TP_ShopRegisterPhaseRecord B WHERE B.OperateCompanyId = A.id ) = 0 ");
            cond.where("ISNULL( A.GDGuid, '' ) = ''");//过滤只选择正常的公司
            LayuiTableVoJA tableVoJA = commonApiServiceByThrOperateCompanyApply.searchLay(cond);
            return tableVoJA;
        }catch (Exception e){
            e.printStackTrace();
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }





    /**
     * 新增
     */
    @RequiresPermissions("tpShopRegisterPhaseRecord:add")
    @PostMapping("/add")
    @ResponseBody
    public LayuiTableVoJA add(HttpServletRequest request,@RequestParam Map<String, Object> params){
        try {
            String chooseId = params.get("chooseId").toString();
            List<String> strList = new ArrayList<>();
            strList.add(chooseId);

            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            //判断店铺注册跟踪阶段有没有设置
            List<TpShopRegisterPhaseSet> setList = new TpShopRegisterPhaseSet().queryList();
            if(setList==null || setList.size()<=0){
                tableVoJA.setMsg("请先设置店铺注册跟踪阶段！");
                tableVoJA.setCode(1);
                return tableVoJA;
            }
            //新增
            int result = tpShopRegisterPhaseRecordService.addList(strList);
            if(result>0){
                tableVoJA.setMsg("新增成功！");
                tableVoJA.setCode(0);
            }else {
                tableVoJA.setMsg("新增失败，请稍后再试！");
                tableVoJA.setCode(1);
            }
            return tableVoJA;
        }catch (Exception e){
            e.printStackTrace();
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setMsg("新增失败，请稍后再试！");
            tableVoJA.setCode(1);
            return tableVoJA;
        }
    }

    /**
     * 完成

    @PostMapping("/edit")
    @ResponseBody
    public R edit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            int res = tpShopRegisterPhaseRecordService.edit(params);
            if(res>0){
                return R.ok("操作成功");
            }else if(res == -1){
                return R.error("操作失败，该阶段设置已被删除！");
            }else{
                return R.error("操作失败，请稍后重试！");
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error("操作失败，请稍后重试！");
        }
    }*/

    /**
     * 完成
     */
    @RequiresPermissions("tpShopRegisterPhaseRecord:finishRecord")
    @PostMapping("/finishRecord")
    @ResponseBody
    public R finishRecord(HttpServletRequest request,@RequestParam Map<String, Object> params){
        try {
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            List<String> strList = new ArrayList<>();
            for(String id :idArr){
                strList.add(id);
            }
    		//获取设置表信息
    		List<TpShopRegisterPhaseSet> setList = new TpShopRegisterPhaseSet().queryList();
    		
            int hasDelSet = 0;//该阶段设置已被删除
            int hasFile = 0;//失败
            for(int i=0;i<strList.size();i++){
                Map<String, Object> paramsNew = new HashMap<>();
                paramsNew.put("id",Integer.parseInt(strList.get(i).toString()));
                int res = tpShopRegisterPhaseRecordService.edit(paramsNew, setList);
                if(res<=0) {
                    if (res == -1) {//该阶段设置已被删除
                        hasDelSet++;
                    } else if (res == -2) {//下一个阶段是分支集合或者分支阶段，但没设置子流程
                        //hasDelSet++;
                    } else {//失败
                        hasFile++;
                    }
                }
            }

            if(hasDelSet==0 && hasFile==0){
                return R.ok("处理成功！");
            }else if(hasDelSet > 0 && hasFile==0){
                if(strList.size()==hasDelSet){
                    return R.error("您所选择的跟踪单处理失败，因为跟踪单对应的阶段设置已被删除，无法完成！");
                }
                return R.ok("部分跟踪单处理失败，这部分跟踪单对应的阶段设置已被删除，无法完成！");
            }else if(hasDelSet == 0 && hasFile > 0){
                if(strList.size()==hasFile){
                    return R.error("您所选择的跟踪单处理失败，请稍后重试！");
                }
                return R.ok("部分跟踪单处理失败，请稍后重试！");
            }else{
                if(strList.size()==hasFile+hasDelSet){
                    return R.error("您所选择的跟踪单处理失败，一部分跟踪单处理失败，另一部分跟踪单对应的阶段设置已被删除，请稍后重试！");
                }
                return R.ok("一部分跟踪单处理失败，另一部分跟踪单对应的阶段设置已被删除，请稍后重试！");
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error("操作失败，请稍后重试！");
        }
    }



    /**
     * 选择店铺
     */
    @RequiresPermissions("tpShopRegisterPhaseRecord:chooseShop")
    @PostMapping("/chooseShop")
    @ResponseBody
    public R chooseShop(HttpServletRequest request, @RequestParam Map<String, Object> params){

        try {
            //修改
            int res = tpShopRegisterPhaseRecordService.setShopOrContent(params);
            if(res>0){
                return R.ok("操作成功");
            }else{
                return R.error("操作失败，请稍后重试！");
            }
        }catch (AuthorizationException e){
            return R.error("操作失败，您没有操作权限！");
        }catch (Exception e){
            e.printStackTrace();
            return R.error("操作失败，请稍后重试！");
        }

    }


    /**
     * 输入工作内容
     */
    @PostMapping("/updateWorkContent")
    @ResponseBody
    public R updateWorkContent(HttpServletRequest request, @RequestParam Map<String, Object> params){

        try {
            //修改
            int res = tpShopRegisterPhaseRecordService.setShopOrContent(params);
            if(res>0){
                return R.ok("操作成功");
            }else{
                return R.error("操作失败，请稍后重试！");
            }
        }catch (AuthorizationException e){
            return R.error("操作失败，您没有操作权限！");
        }catch (Exception e){
            e.printStackTrace();
            return R.error("操作失败，请稍后重试！");
        }

    }


    /**
     * 删除
     */
    @RequiresPermissions("tpShopRegisterPhaseRecord:delete")
    @PostMapping("/deleteTrue")
    @ResponseBody
    public R deleteTrue(HttpServletRequest request, HttpServletResponse response,
                        @RequestParam Map<String, Object> params) {
        try {
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            //删除
            for(int i=0;i<idArr.length;i++){
                tpShopRegisterPhaseRecordService.deleteTpShopRegisterPhaseRecord(Long.parseLong(idArr[i]));
            }
            //tpShopRegisterPhaseRecordService.deleteTpShopRegisterPhaseRecord(operateCompanyId);
            return R.ok("删除成功!");
        }catch (Exception e){
            e.printStackTrace();
            return R.error("删除失败，请稍后重试！");
        }
    }

    /**
     *  详情页面
    */
    @RequestMapping("/getDeatilByCompanyId")
    @ResponseBody
    public LayuiTableVoJA getDeatilByCompanyId(HttpServletRequest request,
                                               @ModelAttribute TpShopRegisterPhaseRecord cond,
                                               @RequestParam Map<String, Object> params){

        try {
            cond = setSeachSql(cond);
            cond.setOrderby("A.Id ASC");//按修改时间排序
            //cond.setOrderby("A.PhaseNum ASC ");//按阶段顺序排序
            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);

            //获取
            JSONArray tableVoJAData = tableVoJA.getData();

            //转换
            List<Map> resList = JSONArray.parseArray(JSON.toJSONString(tableVoJAData),Map.class);
            List<Map<String, Object>> resListNew = new ArrayList();
            resList.forEach(item-> resListNew.add(item));

            //处理数据
            resList = setList(resListNew);
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resList));
            tableVoJA.setData(jsonArray);


            return tableVoJA;

        }catch (Exception e){
            e.printStackTrace();
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setMsg("获取失败，请稍后再试！");
            tableVoJA.setCode(1);
            return tableVoJA;
        }

    }
}